﻿using StandardManager.DB;
using StandardManager.DBItems;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Reflection.Metadata.BlobBuilder;

namespace StandardManager.Forms
{
    /// <summary>
    /// https://xxlllq.github.io/pdf2img/
    /// 如果需要界面，需要移除ExpertPdf.PdfToImage
    /// </summary>
    public partial class NewStandardForm : Form
    {
        public NewStandardForm()
        {
            InitializeComponent();

            this.label2.Visible = false;
            this.button2.Visible = false;
            this.button7.Visible = false;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "*.pdf|*.pdf";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.textBoxFileName.Text = openFileDialog.FileName;
                if (CheckFileNameOk(out string currentFileName) == false)
                {
                    MessageBox.Show("文件名称可能不合适，请调整或点击调整按钮。");
                    return;
                }
                OpenFile();
            }
        }

        private void OpenFile()
        {
            var inFile = Path.ChangeExtension(this.textBoxFileName.Text, ".in");
            if (File.Exists(inFile))
            {
                var str = File.ReadAllLines(inFile);
                this.textBoxBookName.Text = str[0];
                this.textBoxCode.Text = str[1];
            }

            var imgDir = Path.Combine(Path.GetDirectoryName(this.textBoxFileName.Text),
                Path.GetFileNameWithoutExtension(this.textBoxFileName.Text) + "\\Images");
            if (Directory.Exists(imgDir))
            {
                this.label2.Visible = false;
                this.button2.Visible = false;
                this.button7.Visible = false;
                GetFirstPage();
            }
            else
            {
                this.label2.Visible = true;
                this.button2.Visible = true;
                this.button7.Visible = true;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var imgDir = Path.Combine(Path.GetDirectoryName(this.textBoxFileName.Text),
                    Path.GetFileNameWithoutExtension(this.textBoxFileName.Text) + "\\Images");
            if (Directory.Exists(imgDir) == false)
            {
                Directory.CreateDirectory(imgDir);
            }
            var imgs = Freeware.Pdf2Png.ConvertAllPages(File.OpenRead(this.textBoxFileName.Text), 300);
            for (var i = 0; i < imgs.Count; i++)
            {
                var bitmap = Image.FromStream(new MemoryStream(imgs[i]));
                bitmap.Save(Path.Combine(imgDir, "image-" + (i + 1) + ".png"));
            }
            GetFirstPage();
            MessageBox.Show("完成");
        }
        private void button7_Click(object sender, EventArgs e)
        {
            var imgDir = Path.Combine(Path.GetDirectoryName(this.textBoxFileName.Text),
                    Path.GetFileNameWithoutExtension(this.textBoxFileName.Text) + "\\Images");
            if (Directory.Exists(imgDir) == false)
            {
                Directory.CreateDirectory(imgDir);
            }
            //var files
            //ExpertPdf.PdfToImage
           /* var converter = new ExpertPdf.PdfToImageConverter();
            var imgs=converter.ConvertToImages(this.textBoxFileName.Text);

            for (var i = 0; i < imgs.Length; i++)
            {
                //var bitmap = Image.FromStream(new MemoryStream(imgs[i]));
                imgs[i].Save(Path.Combine(imgDir, "image-" + (i + 1) + ".png"));
            }
            GetFirstPage();*/
            MessageBox.Show("完成");
        }

        private void GetFirstPage()
        {
            var imgDir = Path.Combine(Path.GetDirectoryName(this.textBoxFileName.Text),
                    Path.GetFileNameWithoutExtension(this.textBoxFileName.Text) + "\\Images");
            var imgs = Path.Combine(imgDir, "image-1.png");
            if (File.Exists(imgs))
            {
                this.pictureBox1.BackgroundImage = Image.FromFile(imgs);
                this.pictureBox1.BackgroundImageLayout = ImageLayout.Stretch;

                var str = RunCmd(imgs);
                this.textBox1.Text = str;
                this.label_ImageCount.Text = new DirectoryInfo(imgDir).GetFiles("*.*").Length + "个";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Books books = new Books()
            {
                BookName = this.textBoxBookName.Text,
                Code = this.textBoxCode.Text,
            };

            ConnectionDatabase_S2 connectionDatabase_S2 = ConnectionDatabase_S2.BuildSqliteConnection(GlobalConfig.Instance.DBFileName);
            connectionDatabase_S2.ExecuteSQL(books.BuildInsertSql());
            connectionDatabase_S2.Dispose();
            MessageBox.Show("完成");

            this.button3.Text = "名称已入库";
            this.button3.Enabled = false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var imgsDir = Path.Combine(Path.GetDirectoryName(this.textBoxFileName.Text),
                    Path.GetFileNameWithoutExtension(this.textBoxFileName.Text) + "\\Images");
            var dirs = new DirectoryInfo(imgsDir);
            var imgs = dirs.GetFiles();
            ConnectionDatabase_S2 connectionDatabase_S2 = ConnectionDatabase_S2.BuildSqliteConnection(GlobalConfig.Instance.DBFileName);

            var existItems = BookContents.GetRecordsCountSql(this.textBoxCode.Text);
            var dt = connectionDatabase_S2.SelectData(existItems);
            List<int> items = new List<int>();
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                items.Add(BookContents.FromDataRowOfPageIndex(dt.Rows[i]).PageIndex);
            }

            for (var i = 0; i < imgs.Length; i++)
            {
                var file = imgs[i].FullName;
                var pageIndex = int.Parse(Path.GetFileNameWithoutExtension(file).Split('-')[1]);
                if (items.Contains(pageIndex))
                {
                    continue;
                }

                string str = RunCmd(file);

                var bitmap1 = Bitmap.FromFile(file);
                var jpgImg = Path.ChangeExtension(file, ".jpg");
                bitmap1.Save(jpgImg, System.Drawing.Imaging.ImageFormat.Jpeg);
                bitmap1.Dispose();

                BookContents bookContents = new BookContents()
                {
                    BookCode = this.textBoxCode.Text,
                    BookContent = str,
                    BookImg = File.ReadAllBytes(jpgImg),
                    PageIndex = pageIndex
                };
                connectionDatabase_S2.InsertData(bookContents.BuildInsertSql(), "BookImg", bookContents.BookImg);
            }
            connectionDatabase_S2.Dispose();

            MessageBox.Show("完成");
        }

        private string RunCmd(string imgFileName)
        {
            // 创建一个新的进程  
            Process process = new Process();
            process.StartInfo.FileName = GlobalConfig.Instance.UmiOCR; // 指定要执行的 .exe 文件路径  
            process.StartInfo.Arguments = string.Format("--path " + imgFileName); // 传递给 .exe 的命令
            process.StartInfo.RedirectStandardOutput = true; // 重定向输出  
            process.StartInfo.UseShellExecute = false; // 不使用操作系统外壳程序启动  
            process.StartInfo.CreateNoWindow = true; // 不创建窗口  
            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            return output;

            // 输出结果  
            //Console.WriteLine(output);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            File.WriteAllText(Path.ChangeExtension(this.textBoxFileName.Text, ".in"),
                this.textBoxBookName.Text + "\r\n" + this.textBoxCode.Text);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if(CheckFileNameOk(out string currentFileName))
            {
                MessageBox.Show("OK,文件名可以");
                return;
            }

            File.Move(this.textBoxFileName.Text, currentFileName);
            this.textBoxFileName.Text = currentFileName;
            MessageBox.Show("OK");
            OpenFile();
        }

        private bool CheckFileNameOk(out string currentFileName)
        {
            currentFileName = this.textBoxFileName.Text;
            var fileName = Path.GetFileNameWithoutExtension(currentFileName);
            fileName = Regex.Replace(fileName, " ", "");
            fileName = Regex.Replace(fileName, "\\+", "-");
            fileName = Regex.Replace(fileName, "《", "");
            fileName = Regex.Replace(fileName, "》", "");
            currentFileName = Path.Combine(Path.GetDirectoryName(currentFileName), fileName + ".pdf");
            if (currentFileName == this.textBoxFileName.Text)
            {
                return true;
            }
            return false;
        }
    }
}
